#pragma once

#include <iostream>
#include <string>
#include "log.hpp"
#include "error.hpp"
#include <sys/epoll.h>

static const int defaultepfd = -1;
static const int gsize = 128;

class Epoller
{
public:
    Epoller()
        : _epfd(defaultepfd)
    {
    }

    void Create()
    {
        _epfd = epoll_create(gsize);
        if (_epfd < 0)
        {
            logMessage(Fatal, "epoll_create error, code: %d, errstring: %s", errno, strerror(errno));
            exit(EPOLL_CREAT_ERR);
        }
    }

    bool AddEvent(int fd,uint16_t event)//将用户数据加入内核
    {
        //用户数据，epoll底层不对该数据进行任何修改，只是为未来就绪返回做准备
        struct epoll_event ev;
        ev.events=event;
        ev.data.fd=fd;
        int n = epoll_ctl(_epfd, EPOLL_CTL_ADD, fd, &ev);
        if(n < 0)
        {
            logMessage(Fatal, "epoll_ctl error, code: %d, errstring: %s", errno, strerror(errno));
            return false;
        }
        return true;
    }

    bool DelEvent(int fd)
    {
        return epoll_ctl(_epfd,EPOLL_CTL_DEL,fd,nullptr)==0;
    }

    bool Wait(struct epoll_event* events,int max,int time)
    {
        return epoll_wait(_epfd,events,max,time);
    }

    int Fd()
    {
        return _epfd;
    }

    void Close()
    {
        if (_epfd != defaultepfd)
        {
            close(_epfd);
        }
    }
    ~Epoller()
    {
    }

private:
    int _epfd;
};